package com.repair.system.controller;

import com.repair.system.entity.CaseLibrary;
import com.repair.system.service.CaseLibraryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/cases")
@RequiredArgsConstructor
public class CaseLibraryController {
    private final CaseLibraryService caseLibraryService;
    
    @GetMapping
    public String listCases(@RequestParam(required = false) String keyword, Model model) {
        if (keyword != null && !keyword.trim().isEmpty()) {
            model.addAttribute("cases", caseLibraryService.searchCases(keyword));
            model.addAttribute("keyword", keyword);
        } else {
            model.addAttribute("cases", caseLibraryService.getAllCases());
        }
        return "case/list";
    }
    
    @GetMapping("/new")
    public String showCreateForm(Model model) {
        model.addAttribute("case", new CaseLibrary());
        return "case/create";
    }
    
    @PostMapping("/save")
    public String saveCase(@ModelAttribute CaseLibrary caseLibrary) {
        caseLibraryService.saveCase(caseLibrary);
        return "redirect:/cases";
    }
    
    @GetMapping("/{id}")
    public String viewCase(@PathVariable Long id, Model model) {
        model.addAttribute("case", caseLibraryService.getCaseById(id));
        return "case/detail";
    }
}
